#!/usr/bin/env python3
# -*- coding: utf-8 -*-


import os
import logging

import regex

gwd = os.getcwd()


def get_data_log_file():
    """Manages data.log (limits its size and create new ones if needed)
    :return: data(x).log to be used
    """
    max_size_mb = 1024 * 102

    in_dir = sorted(os.listdir())

    data_logs_in_dir = []

    for file_in_dir in in_dir:
        if regex.search('data\d{0,}.log', file_in_dir) is not None:
            data_logs_in_dir.append(file_in_dir)

    num_of_data_log = len(data_logs_in_dir)

    if num_of_data_log >= 1:
        newest_data_log_file = data_logs_in_dir[-1]
        data_log_size = (os.path.getsize(newest_data_log_file))

        if data_log_size <= max_size_mb:
            return newest_data_log_file

        else:
            return 'data{}.log'.format(num_of_data_log)

    else:
        return 'data.log'


def get_logger(logger_name=None):
    """Basic logging settings
    :return: Logger ready to print to stdout and data.log
    """
    logger = logging.getLogger(logger_name)

    logger.setLevel(logging.INFO)

    formater = logging.Formatter('%(asctime)s - {}/%(filename)s:%(lineno)s (%(levelname)s) %(message)s'.format(gwd))

    file_handler = logging.FileHandler(get_data_log_file())
    console_handler = logging.StreamHandler()

    file_handler.setFormatter(formater)
    console_handler.setFormatter(formater)

    logger.addHandler(console_handler)
    logger.addHandler(file_handler)

    return logger
